package com.arrogames.rgblabyrinth.model.storage {
	import flash.net.SharedObject;
	import flash.net.registerClassAlias;
	
	import org.as3commons.logging.api.ILogger;
	import org.as3commons.logging.api.getLogger;
	
	/**
	 * ...
	 * @author Robin van den Bogaard
	 */
	public class RGBStorage {
		
		private static const LOG:ILogger = getLogger(RGBStorage);
		
		private static const RGBSTORAGE:String = "RGBSTORAGE.debugx";
		private var soClient:SharedObject;
		
		private var _savegames:Array;
		
		public function RGBStorage() {
			registerClassAlias("com.arrogames.rgblabyrinth.GameMetaData", GameMetaData);
			
			soClient = SharedObject.getLocal(RGBSTORAGE);
			if (!soClient.data.initiated) {
				initializeSharedObject();
			}
			
			/* reset all savegames
			_savegames = [];
			saveSharedObject();
			*/
			
			readSharedObject();
		}

		public function addSaveGame(game:GameMetaData):void {
			_savegames.push(game);
			saveSharedObject();
		}
		
		public function removeGame(gameToBeRemoved:GameMetaData):void {
			var index:int = -1;
			var game:GameMetaData = null;
			for (var i:int = 0; i < _savegames.length && index == -1; i++) {
				game = _savegames[i] as GameMetaData;
				if (game === gameToBeRemoved) {
					index = i;
				}
			}
			if (index > -1) {
				_savegames.splice(index, 1);
			}
			saveSharedObject();
		}
		
		private function initializeSharedObject():void {
			LOG.debug("Initalised new shared object");
			soClient.data.initiated = true;
			soClient.data.savegames = [];
			soClient.flush();
		}
		
		private function saveSharedObject():void {
			LOG.debug("Saving shared object");
			soClient.data.savegames = _savegames;
			soClient.flush();
		}
		
		private function readSharedObject():void {
			_savegames = soClient.data.savegames;
			LOG.debug("Loaded shared object: {0} games found", [_savegames.length]);
		}
		
		public function get savegames():Array { return _savegames; }
	}

}